/**
 * Created by qunxing.du on 2016/8/16.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.pollution.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hw.one.collect.message.Message;
import com.hw.one.collect.message.ResultMessage;
import com.hw.one.collect.model.DataConstants;
import com.hw.one.collect.model.DataSrcType;
import com.hw.one.collect.pollution.server.data.PollutionDataService;
import com.hw.one.collect.resource.BaseContext;
import com.hw.one.collect.util.ConvertUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 转换数据处理器
 */
public class PollutionTransformDataHandler extends ChannelInboundHandlerAdapter {
    private static Logger log = Logger.getLogger(PollutionTransformDataHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Map<String,Object> receivedData = ConvertUtil.toMap(msg);
        String type = (String) receivedData.get("type");
        String table = (String) receivedData.get("table");
        if(DataSrcType.POLLUTION.name().equals(type)){
            Object data = receivedData.get("data");
            List<Map> list = ConvertUtil.toList(data);

            String collectionName = table+ DataConstants.TRANS_SUFFIX;

            PollutionDataService pollutionDataService = (PollutionDataService) BaseContext.getService("pollutionDataService");
            pollutionDataService.insertTransFormedExhaust(collectionName,list);

            success(ctx);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("异常：",cause);
        Message resultMsg = new ResultMessage("999","error");
        ctx.writeAndFlush(JSON.toJSONString(resultMsg));
    }
    private void success(ChannelHandlerContext ctx){
        Message resultMsg = new ResultMessage("111","success");
        ctx.writeAndFlush(JSON.toJSONString(resultMsg));
    }
}
